package com.konne.nightmare.FastPublicOpinion.http;

import android.content.Context;

import androidx.annotation.NonNull;

import com.google.gson.JsonParseException;
import com.konne.nightmare.FastPublicOpinion.utils.ToastUtil;
import com.konne.nightmare.FastPublicOpinion.utils.MMKVUtils;
import com.konne.nightmare.FastPublicOpinion.utils.Utils;
import com.socks.library.KLog;

import org.json.JSONException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;


public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {

    private static final String tag = BaseObserver.class.getSimpleName();


    private Context mContext;


    //对应HTTP的状态码
    private static final int UNAU = 402;
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    //出错提示
    private final String networkMsg = "网络错误";
    private final String cookieOutMsg = "登录过期，请重新登录";
    private final String parseMsg = "服务器数据解析错误";
    private final String unknownMsg = "未知错误";
    private final String connectMsg = "连接服务器错误,请检查网络";
    private final String connectOutMsg = "连接服务器超时,请检查网络";


    protected BaseObserver(Context context) {
        this.mContext = context;

    }

    protected BaseObserver() {
    }

    @Override
    public void onNext(BaseResponse<T> tBaseEntity) {


        //code 判断
        if (tBaseEntity.isSuccess()) {
            try {
                onSuccess(tBaseEntity);
            } catch (Exception e) {
                e.printStackTrace();
                KLog.d(Utils.TAG, e);
            }
        } else {
            ToastUtil.showToast(tBaseEntity.getMsg());
            switch (tBaseEntity.getCode()) {
                case 401:
                    startLogin();
                    break;
                default:
                    try {
//                        ToastUtil.showToast("服务器错误");
                        onFailure(tBaseEntity.getMsg(), false);
                        KLog.d("stcLook", tBaseEntity.getMsg());
                    } catch (Exception e) {
                        e.printStackTrace();
                        KLog.d(Utils.TAG, e);
                    }
                    break;
            }
        }
    }


    /**
     * 返回成功
     *
     * @param t
     */
    protected abstract void onSuccess(BaseResponse<T> t) throws Exception;

    /**
     * 返回成功了,但是code错误
     *
     * @param error
     */
    protected void onCodeError(int error) {
    }

    @Override
    public void onComplete() {
    }


    @Override
    public void onError(@NonNull Throwable e) {
        Throwable throwable = e;
        //获取最根源的异常
        while (throwable.getCause() != null) {
            e = throwable;
            throwable = throwable.getCause();
        }
        String error = null;
        if (e instanceof ConnectException) {
            error = connectMsg;
        } else if (e instanceof HttpException) {
            error = e.getLocalizedMessage() + "";
        } else if (e instanceof ApiException) {
            ApiException apiException = (ApiException) e;
            switch (apiException.getErrorCode()) {


                case "10007":
                    error = parseMsg;
                    break;
                case "10008":
                    error = cookieOutMsg;
                    //       IntentUtil.showLoginActivity(AppActivityManager.getInstance().getTopActivity());
                    break;
                case "11111":
                    error = cookieOutMsg;
                    //       IntentUtil.showLoginActivity(AppActivityManager.getInstance().getTopActivity());
                    break;
                default:
                    error = e.getLocalizedMessage();
            }
        } else if (e instanceof JsonParseException
                || e instanceof JSONException) {
            error = parseMsg;
        } else if (e instanceof IOException) {
            if (e instanceof SocketTimeoutException) {
                error = connectOutMsg;
            } else {
                if ("Canceled".equals(e.getMessage()) || "Socket closed".equals(e.getMessage()))
                    return;
                else
                    error = connectMsg;
            }
        } else {
            error = e.getLocalizedMessage();
        }

        try {
            KLog.d(Utils.TAG, error);
            onFailure(error, false);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }


    /**
     * 返回失败
     *
     * @param error
     * @param isNetWorkError 是否是网络错误
     */
    protected abstract void onFailure(String error, boolean isNetWorkError) throws Exception;

    public static void startLogin() {
        MMKVUtils.clearAllMMKV();
    }

    @Override
    public void onSubscribe(Disposable d) {
    }
}
